package adapters

import (
	"ai-gateway/common"
	"ai-gateway/db"
	"ai-gateway/proto"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// DeepSeekAdapter 实现AIAdapter接口，适配DeepSeek API
type DeepSeekAdapter struct{}

// Call 调用DeepSeek API，返回统一格式的响应
func (d *DeepSeekAdapter) Call(ctx context.Context, req *proto.AIRequest) (*proto.AIResponse, error) {
	// 从数据库获取DeepSeek的配置
	var config struct {
		ApiKey     string  `db:"api_key"`
		ApiUrl     string  `db:"api_url"`
		TokenPrice float64 `db:"token_price"`
	}
	err := db.DB.Get(&config, "SELECT api_key, api_url, token_price FROM provider_configs WHERE provider = 'deepseek'")
	if err != nil {
		return nil, fmt.Errorf("未找到DeepSeek配置: %v", err)
	}

	// 构造DeepSeek API要求的请求格式
	// 参考：https://api.deepseek.com/docs#operation/ChatCompletion
	requestBody := map[string]interface{}{
		"model": "deepseek-chat", // 正确的模型名称
		"messages": []map[string]string{
			{"role": "user", "content": req.Prompt}, // 必须用messages数组，而非prompt
		},
		"max_tokens": 1024,
	}
	jsonBody, err := json.Marshal(requestBody)
	if err != nil {
		return nil, fmt.Errorf("请求体序列化失败: %v", err)
	}

	// 发起HTTP请求
	httpReq, err := http.NewRequestWithContext(ctx, "POST", config.ApiUrl, bytes.NewBuffer(jsonBody))
	if err != nil {
		return nil, fmt.Errorf("创建请求失败: %v", err)
	}
	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("Authorization", "Bearer "+config.ApiKey)

	// 发送请求并检查状态码
	client := &http.Client{}
	resp, err := client.Do(httpReq)
	if err != nil {
		return nil, fmt.Errorf("调用API失败: %v", err)
	}
	defer resp.Body.Close()

	// 读取原始响应（用于调试）
	respBody, _ := io.ReadAll(resp.Body)
	rawResp := string(respBody)
	common.Logger.Debug().Str("raw_resp", rawResp).Msg("DeepSeek原始响应")

	// 检查非200状态码（如401、400）
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("API返回错误（状态码: %d）: %s", resp.StatusCode, rawResp)
	}

	// 解析DeepSeek的响应
	var deepseekResp struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"` // 生成的内容在choices[0].message.content
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			TotalTokens int `json:"total_tokens"` // Token消耗在usage.total_tokens
		} `json:"usage"`
	}
	if err := json.Unmarshal(respBody, &deepseekResp); err != nil {
		return nil, fmt.Errorf("解析响应失败: %v（原始响应: %s）", err, rawResp)
	}

	// 检查是否有生成结果
	if len(deepseekResp.Choices) == 0 {
		return nil, fmt.Errorf("API未返回有效结果")
	}

	// 转换为统一响应格式
	totalTokens := deepseekResp.Usage.TotalTokens
	return &proto.AIResponse{
		Result:     deepseekResp.Choices[0].Message.Content,
		Provider:   "deepseek",
		TokenUsed:  int32(totalTokens),
		Cost:       int64(float64(totalTokens) * config.TokenPrice * 100), // 转换为分
		IsFinished: true,
	}, nil
}

// 注册适配器
func init() {
	RegisterAdapter("deepseek", &DeepSeekAdapter{})
}
